package org.jxy.study.rpc.netty.hander;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.jxy.study.rpc.message.DataMsg;
import org.jxy.study.rpc.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author : porteryao
 * @description : 根据入参将DataMsg其中数据转换为请求、响应数据
 * @date : 2021/3/12 14:14
 */
public class DataMsgToRequestOrResponseConvert extends SimpleChannelInboundHandler<DataMsg> {
    private Logger logger= LoggerFactory.getLogger(DataMsgToRequestOrResponseConvert.class);
    //需要转换目标类，即Response 或者 Request
    private Class<?> target;

    public DataMsgToRequestOrResponseConvert(Class<?> target) {
        this.target = target;
    }

    protected void channelRead0(ChannelHandlerContext ctx, DataMsg msg) throws Exception {
        final byte[] data = msg.getData();
        Object object = JsonUtil.bytesToObject(data, target);
        ctx.fireChannelRead(object);
        logger.info("入参数据：{}",JsonUtil.objectToJsonString(object));
    }
}
